package jp.sourceforge.akjrcp.potrace;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.dropsomething.DirectoryBasedDropSomething;
import jp.sourceforge.akjrcp.dropsomething.DropsomethingTab;
import jp.sourceforge.akjrcp.dropsomething.IDropSomething;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegUtils;
import jp.sourceforge.akjrcp.ui.DirectryBasedExecuterListener;
import jp.sourceforge.akjrcp.ui.FileOverwriteControler;
import jp.sourceforge.akjrcp.ui.GenericParameters;
import jp.sourceforge.akjrcp.ui.GenericParametersFieldEditor;
import jp.sourceforge.akjrcp.ui.GenericParametersSaveDialog;
import jp.sourceforge.akjrcp.ui.GenericParametersTableViewer;
import jp.sourceforge.akjrcp.ui.param.ParamBoolean;
import jp.sourceforge.akjrcp.ui.param.ParamColor;
import jp.sourceforge.akjrcp.ui.param.ParamCombo;
import jp.sourceforge.akjrcp.ui.param.ParamItem;
import jp.sourceforge.akjrcp.ui.param.ParamItemActionListener;
import jp.sourceforge.akjrcp.ui.param.ParamSpinner;
import jp.sourceforge.akjrcp.ui.param.ParamSpinnerAndScale;
import jp.sourceforge.akjrcp.util.image.ImageUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.core.runtime.Preferences.PropertyChangeEvent;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

public class PotraceTabBuilder implements IDropSomething{
	public static Log log=LogFactory.getLog(PotraceTabBuilder.class);
	private FileOverwriteControler fileOverwriteControler;
	
	
	
	
	public static final String POTRACE_CONVERT="potraceconvert";
	
	private DropsomethingTab dtab;
	private CTabItem tabItem1 ;
	
	public void createControl(final ViewPart part,final CTabFolder tab) {
		if(dtab==null){
			//deley create control
			dtab=new PotraceConvertTab(tab,SWT.NULL);
			dtab.setViewPart(part);
			tabItem1.setControl(dtab);
		}
	}
	public void createTab(ViewPart part, CTabFolder tab) {
		Akj_betasPlugin.getDefault().getPreferenceStore().setDefault("", "");
		 tabItem1 = new CTabItem(tab, SWT.NONE);
		tabItem1.setText(Messages.getString("potraceconvert.tab"));
		
		
	
		
		
		fileOverwriteControler=new FileOverwriteControler(tab.getShell());
	}
	
	public class PotraceConvertTab extends DirectoryBasedDropSomething{

		private PotraceExecuter potraceExecuter;

		private Label dragHere;

		

		private String currentTarget;
		
		//private List buttonList;
		
		
	//	private Button twoPass;
		
		public PotraceConvertTab(Composite parent, int style) {
			super(parent, style);
			
			
		}

		private List settingList;

		private GenericParametersTableViewer tableViewer;
		private List<ParamItem> paramList;

		private Button saveSetting;
		
		ItemModifyCheck itemModifyCheck;
		public void addParamList(ParamItem item){
			paramList.add(item);
			item.setParamItemActionListener(itemModifyCheck);
		}
		
		public class ItemModifyCheck implements ParamItemActionListener{

			public void paramItemModified(ParamItem source) {
				boolean modified=false;
				for (int i = 0; i < paramList.size(); i++) {
					ParamItem item=paramList.get(i);
					if(item.isModified()){
						//log.info("modified:"+item.getKey());
						modified=true;
						break;
					}
					
				}
				//log.info("enabled:"+modified);
				saveSetting.setEnabled(modified);
			}
			
		}
		public class SelectChanged implements ISelectionChangedListener{

			public void selectionChanged(SelectionChangedEvent event) {
				tableSelectionChanged();
			}
			
		}
		
		public Map<String,String> toNewParameterMap(){
			Map<String,String> parameterMap=new HashMap<String,String>();
			for (int i = 0; i < paramList.size(); i++) {
				ParamItem item=paramList.get(i);
				if(item.getValue().length()>0){
					parameterMap.put(item.getKey(), item.getValue());
				}
			}
			return parameterMap;
		}
		
		public void tableSelectionChanged(){
			GenericParameters parameters;
			saveSetting.setEnabled(false);//changed
			int selection=tableViewer.getTable().getSelectionIndex();
			if(selection>=0){
			log.info("table item changed:"+selection);
			parameters=(GenericParameters) tableViewer.getTable().getItem(tableViewer.getTable().getSelectionIndex()).getData();
			log.info("size:"+paramList.size());
			}else{
				//setDefault
				parameters=new GenericParameters();
				
				parameters.set("POTRACE_USE", ""+1);
				parameters.set("MKBITMAP_USE", ""+1);
				
				parameters.set("t", ""+2);
				parameters.set("a", ""+1);
				parameters.set("n", "");//any value become a true
				parameters.set("O", ""+0.2);
				parameters.set("u", ""+10);
				parameters.set("z", "minority");
				parameters.set("C", "#000000");
				
				
				
				parameters.set("MKBITMAP_t", ""+0.45);
				parameters.set("MKBITMAP_f", ""+4);
				parameters.set("MKBITMAP_s", ""+2);
				parameters.set("MKBITMAP_i", "");//false
				
				parameters.set("GLOBAL_backgroundColor", "#ffffff");
				parameters.set("GLOBAL_line_transparent", "100");
				parameters.set("GLOBAL_image_transparent", "100");
				parameters.set("GLOBAL_bluar_image", "1");
				
				
				
				
				
			}
			
			Map map=parameters.getParameters();
			for (int i = 0; i < paramList.size(); i++) {
				ParamItem item=paramList.get(i);
				String value=(String) map.get(item.getKey());
				if(value!=null){
					log.info(item.getKey()+","+value);
					item.setValue(value);
				}else{
					item.setValue("");
				}
			}
			saveSetting.setEnabled(false);//changed
		}
		
		public class GenericSave implements SelectionListener {

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				GenericParameters parameter=tableViewer.getCurrentSelection();
				GenericParametersSaveDialog dialog=new GenericParametersSaveDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
				
				if(parameter==null){
					
				}else{
				String newName=tableViewer.copiedName(parameter);
				dialog.setName(newName);
				dialog.setComment(parameter.getComment());
				}
				int ret=dialog.open();
				int selection;
				if(ret==Dialog.OK){
					log.info("Save:"+dialog.isSaveOverwrite());
					Map newMap=toNewParameterMap();
					if(dialog.isSaveOverwrite()){
//						overwrite or copy
						parameter.setParameters(newMap);
						parameter.setComment(dialog.getComment());
						selection=tableViewer.getTable().getSelectionIndex();
					}else{
						GenericParameters newParam=new GenericParameters(newMap);
						newParam.setName(dialog.getName());
						newParam.setComment(dialog.getComment());
						
						tableViewer.getGenericParameters().add(newParam);
						tableViewer.refresh();//
						
						selection=tableViewer.getTable().getItemCount()-1;//added item.
					}
					//store data
					
					GenericParameters infos[] = (GenericParameters[]) tableViewer.getGenericParameters().toArray(new GenericParameters[0]);
					//String oldValue=getPreferenceStore().getString(H264SettingPage.EXPORT_H264_SETTINGS);
					String newValue=GenericParametersFieldEditor.toStoreString(infos);
					//set only difference
					
					getPreferenceStore().setValue(PotraceSettingPage.EXPORT_POTRACE_SETTINGS,newValue);
					
					//save store
					//maybe selection change ,what should i do.remember and reselect.
					tableViewer.getTable().setSelection(selection);
					tableSelectionChanged();
					//update value;
				}
			}

		}

		private String selectedExport="png";
		private class ExportSelect implements SelectionListener{

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				selectedExport=((Button)e.getSource()).getText();
			}
			
		}
		private Button createRadio(Composite parent,String key){
			Button svg=new Button(parent,SWT.RADIO);
			ExportSelect se=new ExportSelect();
			svg.addSelectionListener(se);
			svg.setText(key);
			return svg;
		}
		public Composite createControls(Composite parent) {
			itemModifyCheck=new ItemModifyCheck();
			
			paramList=new ArrayList<ParamItem>();
			Composite composite=new Composite(parent,SWT.NULL);
			composite.setLayout(new GridLayout(1,true));
			
			Composite listComposite=new Composite(composite,SWT.NULL);
			listComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			listComposite.setLayout(new GridLayout(2,false));
			
			List list=GenericParametersTableViewer.loadList(getPreferenceStore().getString(PotraceSettingPage.EXPORT_POTRACE_SETTINGS));
			
			GridData gd = new GridData(GridData.FILL_HORIZONTAL);
			//gd.minimumHeight=40;
			gd.heightHint=40;
			//gd.grabExcessVerticalSpace=true;
			tableViewer = new GenericParametersTableViewer(listComposite);
			tableViewer.getTable().setLayoutData(gd);
			tableViewer.setGenericParametersList(list);
			
			tableViewer.addSelectionChangedListener(new SelectChanged());
			
			
			saveSetting = new Button(listComposite,SWT.NULL);
			saveSetting.setText(Messages.getString("h264converter.save"));
			saveSetting.setEnabled(false);
			saveSetting.addSelectionListener(new GenericSave());
			
			//buttonList=new ArrayList();
			settingList=new ArrayList();
			setPreferenceKey(POTRACE_CONVERT);
			
			SavePreferenceStore savePreference=new SavePreferenceStore();//for save controls
			
			
			CTabFolder tab = new CTabFolder(composite, SWT.BOTTOM|SWT.FLAT);
			GridData gd2=new GridData(GridData.FILL_BOTH);
			
			tab.setLayoutData(gd2);
			
			Composite basicComposite=new Composite(tab,SWT.NONE);
			basicComposite.setLayout(new GridLayout(1,true));
			CTabItem tabItem1 = new CTabItem(tab, SWT.NONE);
			
			
			
			tabItem1.setText(Messages.getString("potraceconvert.basic"));
			
			tabItem1.setControl(basicComposite);
			
			createDirectoryInfo(basicComposite);
			/*
			twoPass = new Button(composite, SWT.CHECK);
			twoPass.setText(Messages.getString("mpegconvert.twopass"));
			//twoPass.setSelection(getPreferenceStore().getBoolean(PREFERENCE_TWO_PASS));
			twoPass.setToolTipText(Messages
					.getString("mpegconvert.twopass_tooltip"));
			twoPass.addSelectionListener(savePreference);
			twoPass.setVisible(false);//now not support
			*/
			
			
			
			
			dragHere=new Label(basicComposite,SWT.NULL);
			dragHere.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			
			Group export=new Group(basicComposite,SWT.NULL);
			export.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			export.setLayout(new GridLayout(9,false));
			export.setText(Messages.getString("potraceconvert.export"));
			createRadio(export,"svg");
			createRadio(export,"ps");
			createRadio(export,"eps");
			createRadio(export,"pdf");
			createRadio(export,"png").setSelection(true);;
			createRadio(export,"jpg");
			createRadio(export,"bmp");
			createRadio(export,"pnm"); //depend of setting
			
			
			int spinnerWidth=145;
			
			
			
			
			
			Group mkbitmapGroup=new Group(basicComposite,SWT.NULL);
			mkbitmapGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			mkbitmapGroup.setText(Messages.getString("potraceconvert.mkbitmap"));
			mkbitmapGroup.setLayout(new GridLayout(2,false));
			
			ParamBoolean useMkbitmap=new ParamBoolean(mkbitmapGroup,SWT.NONE,"MKBITMAP_USE",Messages.getString("potraceconvert.use_mkbitmap"));
			addParamList(useMkbitmap);
			
			Composite p1=new Composite(mkbitmapGroup,SWT.NULL);
			p1.setLayout(new GridLayout(3,false));
			ParamSpinner mkbitmapS=new ParamSpinner(p1,SWT.NONE,"MKBITMAP_s","size");
			mkbitmapS.setDigits(0);
			mkbitmapS.setMaximum(16); //todo change just spin
			mkbitmapS.setMinimum(1);
			addParamList(mkbitmapS);
			
			
			
			ParamBoolean param_g=new ParamBoolean(p1,SWT.NONE,"MKBITMAP_g","grey");
			addParamList(param_g);
			
			ParamBoolean param_i=new ParamBoolean(p1,SWT.NONE,"MKBITMAP_i","invert");
			addParamList(param_i);
			
			ParamSpinnerAndScale mkbitmapF=createParamSpinnerAndScale(mkbitmapGroup,SWT.NONE,"MKBITMAP_f","high pass filter",spinnerWidth);
			mkbitmapF.setDigits(0);//0 is -n (no filter)
			mkbitmapF.setMaximum(50);//
			mkbitmapF.setMinimum(0);
			addParamList(mkbitmapF);
			
			ParamSpinnerAndScale mkbitmapT=new ParamSpinnerAndScale(mkbitmapGroup,SWT.NONE,"MKBITMAP_t","-t");
			Image bgImage=ImageUtils.loadImage(Akj_betasPlugin.PLUGIN_ID, "icons/tbg32.png");
			//log.info(bgImage);
			mkbitmapT.getSpinnerAndScale().getScale().setBackgroundImage(bgImage);
			
			GridData data=new GridData(GridData.FILL_HORIZONTAL);
			//data.horizontalSpan=3;
			data.widthHint=400;
			mkbitmapT.getSpinnerAndScale().setLayoutData(data);
			mkbitmapT.setDigits(3);
			mkbitmapT.setMaximum(1);
			mkbitmapT.setMinimum(0.001); //more width
			addParamList(mkbitmapT);
			
			
			
		
			
			
			
			
			
			Group potraceG=new Group(basicComposite,SWT.NULL);
			potraceG.setLayout(new GridLayout(4,true));
			potraceG.setText(Messages.getString("potraceconvert.potrace"));
			
			ParamBoolean usePotrace=new ParamBoolean(potraceG,SWT.NONE,"POTRACE_USE",Messages.getString("potraceconvert.use_potrace"));
			addParamList(usePotrace);
			
			ParamBoolean param_n=new ParamBoolean(potraceG,SWT.NONE,"n","n");
			addParamList(param_n);
			param_n.setToolTipText("longcurve            - turn off curve optimization");
			ParamCombo param_z= new ParamCombo(potraceG,SWT.NONE,"z","z",
					new String[]{"black","white","right","left","minority","majority"});
			addParamList(param_z);
			param_z.setToolTipText("turnpolicy <policy>  - how to resolve ambiguities in path decomposition");
			
			
			new Label(potraceG,SWT.NULL);//dummy
			
			
			
			//how to set default value?
			ParamSpinnerAndScale param_t=createParamSpinnerAndScale(potraceG,SWT.NONE,"t","t",spinnerWidth);
			param_t.setMaximum(300);
			param_t.setMinimum(1);
			addParamList(param_t);
			param_t.setToolTipText("turdsize <n>         - suppress speckles of up to this size (default 2)");
			
			ParamSpinnerAndScale param_a=createParamSpinnerAndScale(potraceG,SWT.NONE,"a","a",spinnerWidth);
			param_a.setDigits(2);
			param_a.setMaximum(1.34);
			
			param_a.setMinimum(0);//-1 not supported yet.
			addParamList(param_a);
			param_a.setToolTipText("alphamax <n>         - corner threshold parameter (default 1)");
			
			
			ParamSpinnerAndScale param_O=createParamSpinnerAndScale(potraceG,SWT.NONE,"O","O",spinnerWidth);
			param_O.setDigits(2);
			param_O.setMaximum(1);
			param_O.setMinimum(0.01);
			addParamList(param_O);
			param_O.setToolTipText("opttolerance <n>     - curve optimization tolerance (default 0.2)");
			
			ParamSpinnerAndScale param_u=createParamSpinnerAndScale(potraceG,SWT.NONE,"u","u",spinnerWidth);
			param_u.setMaximum(100);
		
			param_u.setMinimum(1);
			addParamList(param_u);
			param_u.setToolTipText("unit <n>             - quantize output to 1/unit pixels (default 10)");
			
			
			
			Composite advancedComposite=new Composite(tab,SWT.NONE);
			advancedComposite.setLayout(new GridLayout(2,false));
			CTabItem tabItem2 = new CTabItem(tab, SWT.NONE);
			tabItem2.setText(Messages.getString("potraceconvert.advanced"));
			
			tabItem2.setControl(advancedComposite);
			
			createAdvancedControl(advancedComposite);
			//bgcolor white
			//color black
			//color transparent
			//image transparent
			//overwrap image
			
			
			
			/*
			Group vgroup=new Group(basicComposite,SWT.NULL);
			vgroup.setLayout(new GridLayout(6,false));
			vgroup.setText("Video");
			GridData vdata=new GridData();
			vdata.minimumHeight=120;
			vdata.grabExcessVerticalSpace=false;
			vgroup.setLayoutData(vdata);
			
			ParamCombo vcodec= new ParamCombo(vgroup,SWT.NONE,"vcodec","vcodec",
					new String[]{"h264","mpeg4","xvid"});
			addParamList(vcodec);
			
			ParamCombo r= new ParamCombo(vgroup,SWT.NONE,"r","rate",
					new String[]{"12","14.895","15","25","29.97","30","ntsc","pal","30000/1001"});
			addParamList(r);
			
			ParamCombo s= new ParamCombo(vgroup,SWT.NONE,"s","size",
					new String[]{"","176x144","176x144","208x176","416x352","208x208","320x240","640x480","720x480"});
//			"160x128","176x96","176x128","176x144","208x176"
			addParamList(s);
			
			ParamCombo b= new ParamCombo(vgroup,SWT.NONE,"b","bitrate(b)",
					new String[]{"384k","700k","768k","1536k","3072k"});
			addParamList(b);
			
			ParamCombo bt= new ParamCombo(vgroup,SWT.NONE,"bt","bt",
					new String[]{"384k","700k","768k","1536k","3072k"});
			addParamList(bt);
			
			ParamCombo bufsize= new ParamCombo(vgroup,SWT.NONE,"bufsize","bufsize",
					new String[]{"224k","384k","700k","768k","1536k","3072k","4096k"});
			addParamList(bufsize);
			
			ParamCombo maxrate= new ParamCombo(vgroup,SWT.NONE,"maxrate","maxrate",
					new String[]{"384k","768k","1000k","1536k","3072k","4000k","10000k"});
			addParamList(maxrate);
			
			ParamCombo vtag= new ParamCombo(vgroup,SWT.NONE,"vtag","vtag",
					new String[]{"XVID","mp4v","DX50"});
			addParamList(vtag);
			
			ParamCombo crf= new ParamCombo(vgroup,SWT.NONE,"crf","crf",
					new String[]{"15","20","26","32","34"});
			addParamList(crf);
			
			ParamCombo level= new ParamCombo(vgroup,SWT.NONE,"level","level",
					new String[]{"13","21","30"});
			addParamList(level);
			
			ParamCombo aspect= new ParamCombo(vgroup,SWT.NONE,"aspect","aspect",
					new String[]{"","4:3","16:9"});
			addParamList(aspect);
			
			ParamBoolean sameq= new ParamBoolean(vgroup,SWT.NONE,"sameq","sameq");
			addParamList(sameq);
			
			ParamBoolean vn= new ParamBoolean(vgroup,SWT.NONE,"vn","vn");
			addParamList(vn);
			
			ParamBoolean deinterlace= new ParamBoolean(vgroup,SWT.NONE,"deinterlace","deinterlace");
			addParamList(deinterlace);
			
			Group agroup=new Group(basicComposite,SWT.NULL);
			agroup.setText("Audio");
			agroup.setLayout(new GridLayout(6,false));
			GridData adata=new GridData();
			adata.minimumHeight=120;
			adata.grabExcessVerticalSpace=false;
			agroup.setLayoutData(adata);
			
			ParamCombo acodec= new ParamCombo(agroup,SWT.NONE,"acodec","acodec",
					new String[]{"aac","mp3"});
			addParamList(acodec);
			
			ParamCombo ab= new ParamCombo(agroup,SWT.NONE,"ab","ab",
					new String[]{"32k","64k","96k","128k","160k"});
			addParamList(ab);
			
			ParamCombo ar= new ParamCombo(agroup,SWT.NONE,"ar","ar",
					new String[]{"","8000","16000","22050","24000","32000","44100","48000"});
			addParamList(ar);
			
			ParamCombo ac= new ParamCombo(agroup,SWT.NONE,"ac","ac",
					new String[]{"","2","1"});
			addParamList(ac);
			
			ParamCombo vol= new ParamCombo(agroup,SWT.NONE,"vol","vol",
					new String[]{"","224","256","288","320","352","384"});
			addParamList(vol);
			
			ParamBoolean an= new ParamBoolean(agroup,SWT.NONE,"an","an");
			
			addParamList(an);
			
			
			
			Composite advancedComposite=new Composite(tab,SWT.NONE);
			advancedComposite.setLayout(new GridLayout(1,true));
			CTabItem tabItem2 = new CTabItem(tab, SWT.NONE);
			tabItem2.setText("Advanced");
			
			tabItem2.setControl(advancedComposite);
			
			
			ParamCheckGroup flags=new ParamCheckGroup(advancedComposite,SWT.NONE,"flags","flags",
					new String[]{"mv4","obmc","qpel","loop","gmc","mv0","part","gray","psnr","naq","ildct","low_delay",
					"alt","trell","bitexact","aic","umv","cbp","qprd","aiv","slice","ilme","scan_offset","cgop"},12);
			addParamList(flags);
			String text="";
			text+="-flags             <flags> EDVA.\n";
			text+="   mv4                     E.V.. use four motion vector by macroblock (mpeg4)\n";
			text+="   obmc                    E.V.. use overlapped block motion compensation (h263+)\n";
			text+="   qpel                    E.V.. use 1/4 pel motion compensation\n";
			text+="   loop                    E.V.. use loop filter\n";
			text+="   gmc                     E.V.. use gmc\n";
			text+="   mv0                     E.V.. always try a mb with mv=<0,0>\n";
			text+="   part                    E.V.. use data partitioning\n";
			text+="   gray                    EDV.. only decode/encode grayscale\n";
			text+="   psnr                    E.V.. error[?] variables will be set during encoding\n";
			text+="   naq                     E.V.. normalize adaptive quantization\n";
			text+="   ildct                   E.V.. use interlaced dct\n";
			text+="   low_delay               EDV.. force low delay\n";
			text+="   alt                     E.V.. enable alternate scantable (mpeg2/mpeg4)\n";
			text+="   trell                   E.V.. use trellis quantization\n";
			text+="   bitexact                EDVAS use only bitexact stuff (except (i)dct)\n";
			text+="   aic                     E.V.. h263 advanced intra coding / mpeg4 ac prediction\n";
			text+="   umv                     E.V.. use unlimited motion vectors\n";
			text+="   cbp                     E.V.. use rate distortion optimization for cbp\n";
			text+="   qprd                    E.V.. use rate distortion optimization for qp selection\n";
			text+="   aiv                     E.V.. h263 alternative inter vlc\n";
			text+="   slice                   E.V..\n";
			text+="   ilme                    E.V.. interlaced motion estimation\n";
			text+="   scan_offset             E.V.. will reserve space for svcd scan offset user data\n";
			text+="   cgop                    E.V.. closed gop\n";

			flags.setToolTipText(text);
			*/
			
			tab.setSelection(0);
			tab.forceFocus();//must for focus tab.
			updateStatus();
			
			
			Akj_betasPlugin.getDefault().getPluginPreferences().addPropertyChangeListener( new PreferenceStoreMonitor());
			
			//select item
			int defaultSelect=getPreferenceStore().getInt(PotraceSettingPage.EXPORT_POTRACE_SETTINGS_INDEX);
			log.info("defaultSelect:"+defaultSelect);
			if(tableViewer.getTable().getItemCount()>defaultSelect){
				tableViewer.getTable().setSelection(Math.max(0,defaultSelect));//this method don't call SelectionChangedListener 
				
				}else{
					if(tableViewer.getTable().getItemCount()>0){
						tableViewer.getTable().setSelection(0);//this method don't call SelectionChangedListener 
					}else{
						log.info("item is empty");
					}
				}
			tableSelectionChanged();
			tableViewer.addSelectionChangedListener(new StoreSelect());
			
			return composite;
		}
		
		private void createAdvancedControl(Composite advanced){
			ParamColor lineColor=new ParamColor(advanced,SWT.NULL,"C",Messages.getString("potrace.lineColor"));
			lineColor.setToolTipText(Messages.getString("potrace.lineColor_tooltip"));
			addParamList(lineColor);
			
			ParamSpinnerAndScale line_transparent=createParamSpinnerAndScale(advanced,SWT.NONE,"GLOBAL_line_transparent",Messages.getString("potrace.line_transparent"),200);
			line_transparent.setMaximum(100);
			line_transparent.setMinimum(1);
			addParamList(line_transparent);
			line_transparent.setToolTipText(Messages.getString("potrace.line_transparent_tooltip"));
			
			ParamColor bgColor=new ParamColor(advanced,SWT.NULL,"GLOBAL_backgroundColor",Messages.getString("potrace.backgroundColor"));
			bgColor.setToolTipText(Messages.getString("potrace.backgroundColor_tooltip"));
			addParamList(bgColor);
		
			ParamSpinnerAndScale image_transparent=createParamSpinnerAndScale(advanced,SWT.NONE,"GLOBAL_image_transparent",Messages.getString("potrace.image_transparent"),200);
			image_transparent.setMaximum(100);
			image_transparent.setMinimum(1);
			addParamList(image_transparent);
			image_transparent.setToolTipText(Messages.getString("potrace.image_transparent_tooltip"));
			
		
			
			
			
			ParamBoolean draw_image=new ParamBoolean(advanced,SWT.NONE,"GLOBAL_draw_image",Messages.getString("potrace.drawImage"));
			draw_image.setToolTipText(Messages.getString("potrace.drawImage_tooltip"));
			addParamList(draw_image);
			
			ParamSpinnerAndScale bluar_image=createParamSpinnerAndScale(advanced,SWT.NONE,"GLOBAL_bluar_image",Messages.getString("potrace.bluar_image"),200);
			bluar_image.setMaximum(100);
			bluar_image.setMinimum(1);
			addParamList(bluar_image);
			line_transparent.setToolTipText(Messages.getString("potrace.bluar_image_tooltip"));
		}
		
		

		private ParamSpinnerAndScale createParamSpinnerAndScale(Composite parent,int style,String key,String label,int width){
			ParamSpinnerAndScale param=new ParamSpinnerAndScale(parent,style,key,label);
			GridData data=new GridData();
			data.widthHint=width;
			param.getSpinnerAndScale().setLayoutData(data);
			return param;
			
		}
		public class StoreSelect implements ISelectionChangedListener{

			public void selectionChanged(SelectionChangedEvent event) {
				getPreferenceStore().setValue(PotraceSettingPage.EXPORT_POTRACE_SETTINGS_INDEX, tableViewer.getTable().getSelectionIndex());
			}
			
		}
		
		public void updateSettingTable(){
			List list=GenericParametersTableViewer.loadList(Akj_betasPlugin.getDefault().getPreferenceStore().getString(PotraceSettingPage.EXPORT_POTRACE_SETTINGS));
			
			
			tableViewer.setGenericParametersList(list);
			
			
		
					if(tableViewer.getTable().getItemCount()>0){
						tableViewer.getTable().setSelection(0);//
						}
		}
		public class PreferenceStoreMonitor implements IPropertyChangeListener {

			public void propertyChange(PropertyChangeEvent event) {
				log.info(event.getProperty());
				if (event.getProperty().equals(PotraceSettingPage.EXPORT_POTRACE_SETTINGS)) {
					updateSettingTable();
				}
			}

			

		}
		


		
		
public class SavePreferenceStore implements SelectionListener{
			
			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				storeControl((Control)e.getSource());
			}
		}
		
		public void restoreControl(Control control){
			IPreferenceStore store=getPreferenceStore();
			//TODO export type
			/*
			if(control==avisynth){
				
				avisynth.setSelection(store.getBoolean(getPreferenceKey()+"."+AVISYNTH));
				
				}
			*/
			/*
			else if(control==twoPass){
					
					twoPass.setSelection(store.getBoolean(getPreferenceKey()+"."+TWO_PASS));
				
					}*/

			
		}
		
		public void selectCombo(CCombo combo,String value){
			int s=combo.getItemCount();
			for (int i = 0; i <s; i++) {
				if(combo.getItem(i).equals(value)){
					combo.select(i);
					break;
				}
			}
		}
		

		public void storeControl(Control control){
			IPreferenceStore store=getPreferenceStore();
			
			//TODO export type
			/*
			if(control==avisynth){
				
				
				store.setValue(getPreferenceKey()+"."+AVISYNTH, avisynth.getSelection());
				}
				*/
				/*else if(control==twoPass){
					
					
					store.setValue(getPreferenceKey()+"."+TWO_PASS, twoPass.getSelection());
					}*/
		}
		

		
		
		public void inconvert(File file) {
			//
			potraceExecuter.execute(new File[]{file});
			//
		}

		
		public void beforeConvert() {
			//check error again!TODO
			
			String mkBitmapPath=Akj_betasPlugin.getDefault().getPreferenceStore().getString(PotraceSettingPage.MKBITMAP_PAHT);
			potraceExecuter = new PotraceExecuter();
			
			
			
			potraceExecuter.setExecuteListener(new PotraceMonitor());
			potraceExecuter.setPotracePath(Akj_betasPlugin.getDefault().getPreferenceStore().getString(PotraceSettingPage.POTRACE_PAHT));
			potraceExecuter.setMkBitmapPath(mkBitmapPath);
			potraceExecuter.setProcessPrinter(Akj_betasPlugin.getDefault().getProcessPrinter());
			
			
			
			//int select=tableViewer.getTable().getSelectionIndex();
			//log.infoselect:"+select);
			//GenericParameters setting=(GenericParameters) tableViewer.getGenericParameters().get(tableViewer.getTable().getSelectionIndex());
			Map<String,String> newMap=toNewParameterMap();
			
			GenericParameters setting=new GenericParameters(newMap);
			
			
			potraceExecuter.setOutputExtension(selectedExport);
			if(selectedExport.equals("pnm")){
				if(setting.getParameters().get("POTRACE_USE")==null && setting.getParameters().get("MKBITMAP_g")==null){
					potraceExecuter.setOutputExtension("pbm");
				}else{
					potraceExecuter.setOutputExtension("pgm");
				}
			}
			
			
			if(selectedExport.equals("png") ||selectedExport.equals("jpg")||selectedExport.equals("bmp")){
				setting.set("b", "postscript");//TODO test
				setting.set("c", "1");//TODO test
			}else{
				
			}
			
			log.info("GLOBAL_draw_image:"+setting.getParameters().get("GLOBAL_draw_image"));
			if(setting.getParameters().get("GLOBAL_draw_image")!=null){
				potraceExecuter.setMixImage(true);
			}else{
				potraceExecuter.setMixImage(false);
			}
			
			if(!setting.getParameters().get("GLOBAL_line_transparent").equals("")){
				potraceExecuter.setLineTransparent((float) (Double.parseDouble(setting.getParameters().get("GLOBAL_line_transparent"))/100));
			}
			
			if(!setting.getParameters().get("GLOBAL_image_transparent").equals("")){
				potraceExecuter.setImageTransparent((float) (Double.parseDouble(setting.getParameters().get("GLOBAL_image_transparent"))/100));
			}
			
			if(!setting.getParameters().get("GLOBAL_backgroundColor").equals("")){
				potraceExecuter.setBgColor(setting.getParameters().get("GLOBAL_backgroundColor"));
			}
			
			if(!setting.getParameters().get("GLOBAL_bluar_image").equals("")){
				potraceExecuter.setBlur((int) Double.parseDouble(setting.getParameters().get("GLOBAL_bluar_image")));
			}
			
			potraceExecuter.setGenericParameters(setting);
			
			
			potraceExecuter.setSameDirectory(samefolder.getSelection());
			potraceExecuter.setBackup(backup.getSelection());
			if(!samefolder.getSelection()){
				potraceExecuter.setExportDir(directoryChooser.getAbsoluteFilePath());
			}
			
		}
		


		public void afterConvert() {
			// TODO Auto-generated method stub
			
		}
		
		public class PotraceMonitor implements DirectryBasedExecuterListener{

			public void beforeConvert() {
				// TODO Auto-generated method stub
				
			}

			public void afterConvert() {
				// TODO Auto-generated method stub
				setProgress(0);
			}

			public void startConvert(File file) {
				setProgress(0);
				
				
			}

			public void endConvert(File file) {
				setProgress(100);
				
			}

			public void faildConvert(File file, String message) {
				Akj_betasPlugin.getDefault().getProcessPrinter().printOutput("[faild-potrace]"+message+","+file.getAbsolutePath()+"\n\n");
			}

			public void printProcess(String line) {
				//Akj_betasPlugin.getDefault().
				Akj_betasPlugin.getDefault().getProcessPrinter().printError(line);
				
				if(FFMpegUtils.isProgressString(line)){
					progressBytes(FFMpegUtils.getProgressSize(line));//progress bar work,call setProgress
				}
			}

			public boolean askOverwrite(File output) {
				
				return FileOverwriteControler.askOverwrite(fileOverwriteControler,output);
			}
			
		}
		//overwrite only work when ffmpeg is available
		public boolean isCanConvert(){
			
			String exePath = MkBitmapUtils.getMkbitmapPath();

			if (exePath==null) {
			setCantConvertStatusbarMessage("potrace.no_mkbitmap");
			return false;
			}
			return super.isCanConvert();
		}

		public void cancelConvert() {
			potraceExecuter.cancel();
		}

		public void updateStatus() {
			
			if(samefolder.getSelection() || directoryChooser.getFile()!=null){
				setMessage(Messages.getString("dropsomething.drag_folder"));
				setCanConvert(true);
			}else{
				setErrorMessage(Messages.getString("dropsomething.choose_folder"));
				setCanConvert(false);
			}
		}
		
		public void setMessage(String text){
			if(dragHere!=null){//before initialize
			dragHere.setForeground(new Color(null,64,255,64));
			dragHere.setText(text);
			}
		}
		public void setErrorMessage(String text){
			if(dragHere!=null){
			dragHere.setForeground(new Color(null,255,0,0));
			dragHere.setText(text);
			}
		}

		public IPreferenceStore getPreferenceStore(){
			return Akj_betasPlugin.getDefault().getPreferenceStore();
		}
		
		public boolean setFocus(){
			return tableViewer.getTable().setFocus();
			
		}
		
	}
	

	

	
	
}
